// 聊天应用JavaScript功能
let currentChatId = 'user1';
let currentTab = 'recent';
let isEmojiPanelOpen = false;
let isRecording = false;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeChat();
    setupEventListeners();
    loadChatHistory();
});

function initializeChat() {
    // 设置当前用户信息
    const userAvatar = document.querySelector('.current-user .user-avatar');
    const username = document.querySelector('.current-user .username');
    
    // 可以从localStorage或API获取用户信息
    const userData = JSON.parse(localStorage.getItem('userData') || '{}');
    if (userData.username) {
        username.textContent = userData.username;
    }
    if (userData.avatar) {
        userAvatar.textContent = userData.avatar;
    }
}

function setupEventListeners() {
    // 输入框自动调整高度
    const messageInput = document.getElementById('messageInput');
    messageInput.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 120) + 'px';
    });

    // 点击空白区域关闭表情面板
    document.addEventListener('click', function(e) {
        const emojiPanel = document.getElementById('emojiPanel');
        const emojiBtn = document.querySelector('.tool-btn[onclick="toggleEmojiPanel()"]');
        
        if (!emojiPanel.contains(e.target) && !emojiBtn.contains(e.target)) {
            emojiPanel.classList.remove('show');
            isEmojiPanelOpen = false;
        }
    });

    // 滚动到底部
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function switchTab(tabName) {
    currentTab = tabName;
    
    // 更新标签状态
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`.tab-btn[onclick="switchTab('${tabName}')"]`).classList.add('active');
    
    // 加载对应内容
    loadTabContent(tabName);
}

function loadTabContent(tabName) {
    const chatList = document.getElementById('chatList');
    
    switch(tabName) {
        case 'recent':
            chatList.innerHTML = `
                <div class="chat-item active" onclick="openChat('user1')">
                    <div class="chat-avatar">
                        <div class="avatar online">👨</div>
                        <div class="unread-count">2</div>
                    </div>
                    <div class="chat-info">
                        <div class="chat-name">张小明</div>
                        <div class="last-message">厦门大学真的很美！</div>
                        <div class="chat-time">10:30</div>
                    </div>
                </div>
                <div class="chat-item" onclick="openChat('user2')">
                    <div class="chat-avatar">
                        <div class="avatar">👩</div>
                    </div>
                    <div class="chat-info">
                        <div class="chat-name">李小红</div>
                        <div class="last-message">鼓浪屿的钢琴博物馆值得一去</div>
                        <div class="chat-time">昨天</div>
                    </div>
                </div>
                <div class="chat-item" onclick="openChat('group1')">
                    <div class="chat-avatar">
                        <div class="avatar group">🏝️</div>
                        <div class="unread-count">1</div>
                    </div>
                    <div class="chat-info">
                        <div class="chat-name">厦门旅游交流群</div>
                        <div class="last-message">王小华: 有人一起去南普陀寺吗？</div>
                        <div class="chat-time">09:15</div>
                    </div>
                </div>
            `;
            break;
        case 'contacts':
            chatList.innerHTML = `
                <div class="chat-item" onclick="openChat('user2')">
                    <div class="chat-avatar">
                        <div class="avatar">👩</div>
                    </div>
                    <div class="chat-info">
                        <div class="chat-name">李小红</div>
                        <div class="last-message">旅游摄影师</div>
                        <div class="chat-time">在线</div>
                    </div>
                </div>
                <div class="chat-item" onclick="openChat('user3')">
                    <div class="chat-avatar">
                        <div class="avatar">👨‍💼</div>
                    </div>
                    <div class="chat-info">
                        <div class="chat-name">旅游向导-小陈</div>
                        <div class="last-message">专业导游</div>
                        <div class="chat-time">离线</div>
                    </div>
                </div>
            `;
            break;
        case 'groups':
            chatList.innerHTML = `
                <div class="chat-item" onclick="openChat('group1')">
                    <div class="chat-avatar">
                        <div class="avatar group">🏝️</div>
                        <div class="unread-count">1</div>
                    </div>
                    <div class="chat-info">
                        <div class="chat-name">厦门旅游交流群</div>
                        <div class="last-message">128人</div>
                        <div class="chat-time">活跃</div>
                    </div>
                </div>
                <div class="chat-item" onclick="openChat('group2')">
                    <div class="chat-avatar">
                        <div class="avatar group">📸</div>
                    </div>
                    <div class="chat-info">
                        <div class="chat-name">厦门摄影爱好者</div>
                        <div class="last-message">56人</div>
                        <div class="chat-time">活跃</div>
                    </div>
                </div>
            `;
            break;
    }
}

function openChat(chatId) {
    currentChatId = chatId;
    
    // 更新聊天列表选中状态
    document.querySelectorAll('.chat-item').forEach(item => {
        item.classList.remove('active');
    });
    event.currentTarget.classList.add('active');
    
    // 加载聊天内容
    loadChatMessages(chatId);
    updateChatHeader(chatId);
    
    // 清除未读消息
    const unreadCount = event.currentTarget.querySelector('.unread-count');
    if (unreadCount) {
        unreadCount.remove();
    }
}

function updateChatHeader(chatId) {
    const chatUserName = document.querySelector('.chat-user-name');
    const chatUserStatus = document.querySelector('.chat-user-status');
    const chatUserAvatar = document.querySelector('.chat-user-avatar .avatar');
    
    const chatData = {
        'user1': { name: '张小明', status: '在线 - 正在输入...', avatar: '👨' },
        'user2': { name: '李小红', status: '在线', avatar: '👩' },
        'user3': { name: '旅游向导-小陈', status: '离线', avatar: '👨‍💼' },
        'group1': { name: '厦门旅游交流群', status: '128人在线', avatar: '🏝️' },
        'group2': { name: '厦门摄影爱好者', status: '56人在线', avatar: '📸' }
    };
    
    const data = chatData[chatId];
    if (data) {
        chatUserName.textContent = data.name;
        chatUserStatus.textContent = data.status;
        chatUserAvatar.textContent = data.avatar;
        
        // 更新在线状态
        if (data.status.includes('在线')) {
            chatUserAvatar.classList.add('online');
        } else {
            chatUserAvatar.classList.remove('online');
        }
    }
}

function loadChatMessages(chatId) {
    const chatMessages = document.getElementById('chatMessages');
    
    // 模拟不同聊天的消息内容
    const messagesData = {
        'user1': `
            <div class="message-group">
                <div class="message received">
                    <div class="message-avatar">👨</div>
                    <div class="message-content">
                        <div class="message-bubble">
                            你好！我刚到厦门，有什么推荐的景点吗？
                        </div>
                        <div class="message-time">10:25</div>
                    </div>
                </div>
            </div>
            <div class="message-group">
                <div class="message sent">
                    <div class="message-content">
                        <div class="message-bubble">
                            欢迎来到厦门！推荐你先去鼓浪屿，那里有很多历史建筑和美丽的海景
                        </div>
                        <div class="message-time">10:26</div>
                    </div>
                    <div class="message-avatar">👤</div>
                </div>
            </div>
            <div class="message-group">
                <div class="message received">
                    <div class="message-avatar">👨</div>
                    <div class="message-content">
                        <div class="message-bubble image-message">
                            <img src="https://via.placeholder.com/200x150/4ecdc4/ffffff?text=厦门大学" alt="厦门大学">
                            <div class="image-caption">厦门大学真的很美！</div>
                        </div>
                        <div class="message-time">10:30</div>
                    </div>
                </div>
            </div>
            <div class="typing-indicator">
                <div class="typing-avatar">👨</div>
                <div class="typing-bubble">
                    <div class="typing-dots">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                </div>
            </div>
        `,
        'user2': `
            <div class="message-group">
                <div class="message received">
                    <div class="message-avatar">👩</div>
                    <div class="message-content">
                        <div class="message-bubble">
                            鼓浪屿的钢琴博物馆值得一去，里面有很多珍贵的古钢琴
                        </div>
                        <div class="message-time">昨天 15:30</div>
                    </div>
                </div>
            </div>
            <div class="message-group">
                <div class="message sent">
                    <div class="message-content">
                        <div class="message-bubble">
                            好的，谢谢推荐！还有其他值得去的地方吗？
                        </div>
                        <div class="message-time">昨天 15:32</div>
                    </div>
                    <div class="message-avatar">👤</div>
                </div>
            </div>
        `,
        'group1': `
            <div class="message-group">
                <div class="message received">
                    <div class="message-avatar">👨‍💼</div>
                    <div class="message-content">
                        <div class="message-bubble">
                            <div class="message-sender">王小华</div>
                            有人一起去南普陀寺吗？明天上午
                        </div>
                        <div class="message-time">09:15</div>
                    </div>
                </div>
            </div>
            <div class="message-group">
                <div class="message received">
                    <div class="message-avatar">👩‍🎓</div>
                    <div class="message-content">
                        <div class="message-bubble">
                            <div class="message-sender">小李</div>
                            我可以去！几点集合？
                        </div>
                        <div class="message-time">09:18</div>
                    </div>
                </div>
            </div>
        `
    };
    
    chatMessages.innerHTML = messagesData[chatId] || '<div class="no-messages">暂无消息</div>';
    
    // 滚动到底部
    setTimeout(() => {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }, 100);
}

function loadChatHistory() {
    // 加载默认聊天
    loadChatMessages(currentChatId);
    updateChatHeader(currentChatId);
}

// 发送消息
function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    
    if (!message) return;
    
    // 添加消息到聊天区域
    addMessageToChat(message, true);
    
    // 清空输入框
    messageInput.value = '';
    messageInput.style.height = 'auto';
    
    // 模拟对方回复
    setTimeout(() => {
        simulateReply();
    }, 1000 + Math.random() * 2000);
}

function addMessageToChat(message, isSent = false) {
    const chatMessages = document.getElementById('chatMessages');
    const messageGroup = document.createElement('div');
    messageGroup.className = 'message-group';
    
    const currentTime = new Date().toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
    });
    
    messageGroup.innerHTML = `
        <div class="message ${isSent ? 'sent' : 'received'}">
            ${!isSent ? '<div class="message-avatar">👨</div>' : ''}
            <div class="message-content">
                <div class="message-bubble">
                    ${message}
                </div>
                <div class="message-time">${currentTime}</div>
            </div>
            ${isSent ? '<div class="message-avatar">👤</div>' : ''}
        </div>
    `;
    
    // 移除打字指示器
    const typingIndicator = chatMessages.querySelector('.typing-indicator');
    if (typingIndicator) {
        typingIndicator.remove();
    }
    
    chatMessages.appendChild(messageGroup);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function simulateReply() {
    const replies = [
        '好的，我了解了！',
        '谢谢你的建议 😊',
        '这个地方确实很不错',
        '我也想去看看',
        '有时间一起去吧！',
        '厦门真的是个美丽的城市',
        '期待和你一起探索更多景点'
    ];
    
    const randomReply = replies[Math.floor(Math.random() * replies.length)];
    addMessageToChat(randomReply, false);
}

// 处理输入框按键
function handleInputKeydown(event) {
    if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
    }
}

function handleInputChange() {
    const messageInput = document.getElementById('messageInput');
    const sendBtn = document.getElementById('sendBtn');
    
    // 根据输入内容调整发送按钮状态
    if (messageInput.value.trim()) {
        sendBtn.style.background = 'linear-gradient(45deg, #ff6b6b, #4ecdc4)';
    } else {
        sendBtn.style.background = 'rgba(255, 255, 255, 0.3)';
    }
}

// 表情面板功能
function toggleEmojiPanel() {
    const emojiPanel = document.getElementById('emojiPanel');
    const toolBtn = event.currentTarget;
    
    isEmojiPanelOpen = !isEmojiPanelOpen;
    
    if (isEmojiPanelOpen) {
        emojiPanel.classList.add('show');
        toolBtn.classList.add('active');
    } else {
        emojiPanel.classList.remove('show');
        toolBtn.classList.remove('active');
    }
}

function showEmojiCategory(category) {
    // 更新分类按钮状态
    document.querySelectorAll('.emoji-cat').forEach(btn => {
        btn.classList.remove('active');
    });
    event.currentTarget.classList.add('active');
    
    // 加载对应分类的表情
    const emojiGrid = document.getElementById('emojiGrid');
    const emojiCategories = {
        'recent': ['😊', '😂', '❤️', '👍', '🎉', '🌟', '🏝️', '🌊'],
        'smileys': ['😊', '😂', '🤣', '😍', '🥰', '😘', '😉', '😎', '🤔', '😴', '😭', '😱'],
        'travel': ['🏝️', '🌊', '🏖️', '🏯', '🎓', '🚢', '✈️', '🗺️', '📸', '🎒', '🌅', '🌺'],
        'objects': ['🎹', '🎯', '📱', '💻', '📷', '🎵', '🍜', '🍰', '☕', '🎁', '💝', '🌈']
    };
    
    const emojis = emojiCategories[category] || emojiCategories['recent'];
    emojiGrid.innerHTML = emojis.map(emoji => 
        `<span class="emoji-item" onclick="insertEmoji('${emoji}')">${emoji}</span>`
    ).join('');
}

function insertEmoji(emoji) {
    const messageInput = document.getElementById('messageInput');
    const cursorPos = messageInput.selectionStart;
    const textBefore = messageInput.value.substring(0, cursorPos);
    const textAfter = messageInput.value.substring(cursorPos);
    
    messageInput.value = textBefore + emoji + textAfter;
    messageInput.focus();
    messageInput.setSelectionRange(cursorPos + emoji.length, cursorPos + emoji.length);
    
    // 触发输入事件以调整高度
    messageInput.dispatchEvent(new Event('input'));
}

// 文件和图片处理
function selectImage() {
    document.getElementById('imageInput').click();
}

function selectFile() {
    document.getElementById('fileInput').click();
}

function handleImageSelect(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const imageMessage = `
                <div class="image-message">
                    <img src="${e.target.result}" alt="用户图片" style="max-width: 200px; border-radius: 8px;">
                </div>
            `;
            addMessageToChat(imageMessage, true);
        };
        reader.readAsDataURL(file);
    }
}

function handleFileSelect(event) {
    const file = event.target.files[0];
    if (file) {
        const fileMessage = `
            <div class="file-message">
                📎 ${file.name} (${(file.size / 1024).toFixed(1)} KB)
            </div>
        `;
        addMessageToChat(fileMessage, true);
    }
}

// 语音录制
function startVoiceRecord() {
    const toolBtn = event.currentTarget;
    
    if (!isRecording) {
        isRecording = true;
        toolBtn.classList.add('active');
        toolBtn.innerHTML = '<span class="icon">🔴</span>';
        
        // 模拟录音
        setTimeout(() => {
            stopVoiceRecord();
        }, 3000);
    } else {
        stopVoiceRecord();
    }
}

function stopVoiceRecord() {
    isRecording = false;
    const toolBtn = document.querySelector('.tool-btn[onclick="startVoiceRecord()"]');
    toolBtn.classList.remove('active');
    toolBtn.innerHTML = '<span class="icon">🎤</span>';
    
    // 添加语音消息
    addMessageToChat('🎤 语音消息 (3秒)', true);
}

// 位置分享
function shareLocation() {
    const locationMessage = '📍 我的位置: 厦门市思明区厦门大学';
    addMessageToChat(locationMessage, true);
}

// 通话功能
function startVideoCall() {
    alert('正在发起视频通话...');
}

function startVoiceCall() {
    alert('正在发起语音通话...');
}

// 聊天信息面板
function showChatInfo() {
    const chatInfoPanel = document.getElementById('chatInfoPanel');
    chatInfoPanel.classList.add('show');
}

function hideChatInfo() {
    const chatInfoPanel = document.getElementById('chatInfoPanel');
    chatInfoPanel.classList.remove('show');
}

// 新建聊天弹窗
function showNewChatModal() {
    const modal = document.getElementById('newChatModal');
    modal.classList.add('show');
}

function hideNewChatModal() {
    const modal = document.getElementById('newChatModal');
    modal.classList.remove('show');
}

function showSearchModal() {
    showNewChatModal(); // 复用新建聊天弹窗
}

function startNewChat(userId) {
    hideNewChatModal();
    openChat(userId);
    
    // 如果是新用户，添加到聊天列表
    const chatList = document.getElementById('chatList');
    const existingChat = chatList.querySelector(`[onclick="openChat('${userId}')"]`);
    
    if (!existingChat) {
        const newChatItem = document.createElement('div');
        newChatItem.className = 'chat-item';
        newChatItem.onclick = () => openChat(userId);
        newChatItem.innerHTML = `
            <div class="chat-avatar">
                <div class="avatar">👤</div>
            </div>
            <div class="chat-info">
                <div class="chat-name">新用户</div>
                <div class="last-message">开始聊天吧！</div>
                <div class="chat-time">刚刚</div>
            </div>
        `;
        chatList.insertBefore(newChatItem, chatList.firstChild);
    }
}

// 点击模态框背景关闭
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal')) {
        e.target.classList.remove('show');
    }
});
